<template>
  <div class="admin-container">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="logo">
        <img src="@/logo/1.png" alt="系统logo" class="logo-img">
      </div>

      <div class="top-nav">
        <!-- 修改导航链接路径 -->
        <router-link to="/admin-home/account-approval" class="nav-item"
          :class="{ 'active': $route.path === '/admin-home/account-approval' }">
          <div>审核</div>
        </router-link>
        <router-link to="/admin-home/user-query" class="nav-item"
          :class="{ 'active': $route.path === '/admin-home/user-query' }">
          <div>查询用户信息</div>
        </router-link>
      </div>

      <div class="header-actions">
        <router-link to="/admin-home"><el-icon class="icon">
            <User />
          </el-icon></router-link>
        <!-- 删除铃铛图标 -->
        <router-link to="/login"><el-icon class="icon">
            <CircleClose />
          </el-icon></router-link>
      </div>
    </el-header>

    <!-- 主内容区域 -->
    <el-main class="content-area">
      <div class="content-wrapper">
        <!-- 仅在访问管理员首页根路径时显示内容 -->
        <div v-show="$route.path === '/admin-home'">
          <!-- 统计卡片区域 -->
          <el-row :gutter="20" class="stat-cards">
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="card-content">
                  <div class="card-title">总用户数</div>
                  <div class="card-value">{{ totalUsers }}</div> <!-- 替换硬编码189 -->
                  <div class="card-trend">
                    <span class="trend-up">+{{ userIncrease }}</span>
                    <span class="trend-text">较上月</span>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="card-content">
                  <div class="card-title">待审核</div>
                  <div class="card-value">{{ pendingUsers }}</div> <!-- 替换硬编码12 -->
                  <div class="card-trend">
                    <span class="trend-down">-{{ pendingDecrease }}</span>
                    <span class="trend-text">较昨日</span>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="card-content">
                  <div class="card-title">活跃用户</div>
                  <div class="card-value">{{ activeUsers }}</div> <!-- 替换硬编码189 -->
                  <div class="card-trend">
                    <span class="trend-up">+{{ activeIncrease }}</span>
                    <span class="trend-text">较昨日</span>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="card-content">
                  <div class="card-title">已冻结</div>
                  <div class="card-value">{{ frozenUsers }}</div>
                  <div class="card-trend">
                    <span class="trend-up">+{{ frozenIncrease }}</span>
                    <span class="trend-text">较昨日</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 图表区域 -->
          <div class="chart-container">
            <el-card class="chart-card">
              <div slot="header" class="card-header">
                <span>用户状态分布</span>
              </div>
              <div id="adminStatusChart" class="chart-content"></div>
            </el-card>
          </div>
        </div>

        <!-- 子路由视图 - 仅在访问子路径时显示 -->
        <router-view v-show="$route.path.startsWith('/admin-home/')" />
      </div>
    </el-main>
  </div>
</template>

<script>
import { User, CircleClose } from '@element-plus/icons-vue';
import { ElHeader, ElMain, ElRow, ElCol, ElCard } from 'element-plus';
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref, watch, onActivated, nextTick, computed } from 'vue';
import { useRoute } from 'vue-router';
import request from '@/utils/request'; // 添加request导入
import { ElMessage } from 'element-plus'; // 添加消息提示组件

export default {
  name: 'AdminHome',
  components: {
    ElHeader, ElMain, ElRow, ElCol, ElCard,
    User, CircleClose
  },
  setup() {
    const route = useRoute();
    const chartInstance = ref(null);
    const forceReinit = ref(false);
    const userStatusData = ref([
      { name: '活跃', value: 0 },
      { name: '已冻结', value: 0 },
      { name: '待审核', value: 0 }
    ]);
    // 添加趋势数据ref
    const trendData = ref({
      userIncrease: 0,
      pendingDecrease: 0,
      activeIncrease: 0
    });

    // 修改图表配置，使用动态数据
    const option = {
      tooltip: { trigger: 'item' },
      legend: { top: '5%', left: 'center' },
      series: [{
        name: '用户状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } },
        labelLine: { show: false },
        data: userStatusData.value // 使用动态数据
      }]
    };

    // 添加用户数据获取方法
    const fetchUserData = async () => {
      try {
        const response = await request.get('/admin/getAllUser');
        if (response.code === 200) {
          // 处理用户状态数据
          const statusMap = {
            'NORMAL': { name: '活跃', value: 0 },
            'FROZEN': { name: '已冻结', value: 0 },
            'PENDING': { name: '待审核', value: 0 }
          };

          // 统计各状态用户数量
          response.data.forEach(user => {
            if (statusMap[user.status]) {
              statusMap[user.status].value++;
            }
          });

          // 更新图表数据
          userStatusData.value = Object.values(statusMap);
          updateChartData();
        } else {
          ElMessage.error('获取用户数据失败: ' + response.msg);
        }
      } catch (error) {
        ElMessage.error('网络错误，无法获取用户数据');
        console.error(error);
      }
    };

    // 添加图表数据更新方法
    const updateChartData = () => {
      if (chartInstance.value) {
        chartInstance.value.setOption({
          series: [{
            data: userStatusData.value
          }]
        });
      }
    };

    // 修改图表初始化函数
    const initChart = async () => {
      // 添加DOM元素存在性检查
      const chartDom = document.getElementById('adminStatusChart');
      if (!chartDom) {
        console.error('图表DOM元素不存在');
        return;
      }

      await nextTick();
      await new Promise(resolve => requestAnimationFrame(resolve));

      const { width, height } = chartDom.getBoundingClientRect();
      if (width * height === 0) {
        chartDom.style.minHeight = '400px';
        chartDom.style.display = 'block';
      }

      if (chartInstance.value && !forceReinit.value) {
        chartInstance.value.resize();
        return;
      }

      chartInstance.value?.dispose();
      chartInstance.value = echarts.init(chartDom);
      chartInstance.value.setOption(option); // 使用动态option
      forceReinit.value = false;

      setTimeout(() => {
        if (!chartInstance.value?._dom.offsetParent) {
          console.error('图表仍不可见，重新挂载');
          forceReinit.value = true;
          initChart();
        }
      }, 300);
    };

    // 修改生命周期钩子
    onMounted(() => {
      // 使用nextTick确保DOM渲染完成
      nextTick(() => {
        fetchUserData();
        initChart();
      });

      const handleResize = () => chartInstance.value?.resize();
      window.addEventListener('resize', handleResize);

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize);
      });
    });

    onUnmounted(() => {
      if (chartInstance.value) {
        chartInstance.value.dispose();
        chartInstance.value = null;
      }
    });

    onActivated(() => {
      forceReinit.value = true;
      initChart();

      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            reuseChartInstance();
            observer.unobserve(entry.target);
          }
        });
      });

      const chartDom = document.getElementById('adminStatusChart');
      if (chartDom) observer.observe(chartDom);

      setTimeout(() => reuseChartInstance(), 500);
    });

    // 添加计算属性
    const totalUsers = computed(() => {
      return userStatusData.value.reduce((sum, item) => sum + item.value, 0);
    });

    const pendingUsers = computed(() => {
      const pendingItem = userStatusData.value.find(item => item.name === '待审核');
      return pendingItem ? pendingItem.value : 0;
    });

    const activeUsers = computed(() => {
      const activeItem = userStatusData.value.find(item => item.name === '活跃');
      return activeItem ? activeItem.value : 0;
    });

    // 修改fetchUserData方法，添加趋势数据处理


    const frozenUsers = computed(() => {
      const frozenItem = userStatusData.value.find(item => item.name === '已冻结');
      return frozenItem ? frozenItem.value : 0;
    });

    // 确保在return中导出所有需要的变量
    return {
      totalUsers,
      pendingUsers,
      activeUsers,
      frozenUsers,
      // 可以添加其他需要在模板中使用的属性
    };
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.admin-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #e9e9e9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  height: 40px;
  width: auto;
  object-fit: contain;
}

.top-nav {
  display: flex;
  flex: 1;
  margin: 0 20px;
  height: 100%;
}

.nav-item {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #333 !important;
  font-size: 14px;
  font-weight: 500;
  position: relative;
  text-decoration: none;
}

.nav-item.active {
  background-color: #dcdcdc;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #409EFF;
  display: block;
}

.header-actions {
  display: flex;
  gap: 20px;
}

.icon {
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.content-area {
  flex: 1;
  background-color: white;
  padding: 20px;
  overflow: auto;
}

/* 新增统计卡片和图表样式 */
.content-wrapper {
  width: 100%;
  height: 100%;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 150px;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 15px;
}

.card-title {
  color: #606266;
  font-size: 14px;
  margin-bottom: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-trend {
  display: flex;
  align-items: center;
}

.trend-up {
  color: #52c41a;
  margin-right: 5px;
}

.trend-down {
  color: #f5222d;
  margin-right: 5px;
}

.chart-container {
  width: 100%;
}

.chart-card {
  height: 400px;
}

.chart-content {
  width: 100%;
  height: calc(100% - 40px);
}
</style>
